package com.baibei.ebec.moments.activity;

import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.baibei.ebec.home.R;
import com.baibei.ebec.home.R2;
import com.baibei.ebec.moments.adapter.CommentsAadapter;
import com.baibei.ebec.sdk.ApiConstant;
import com.baibei.model.UserInfo;
import com.baibei.ui.AppUI;
import com.baibei.widget.FixedEditText;
import com.baibei.widget.NestedExpandableListview;
import com.blankj.utilcode.utils.ToastUtils;
import com.google.gson.Gson;
import com.rae.swift.session.SessionManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MomentsDetailActivity extends AppCompatActivity {

    @BindView(R2.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R2.id.tv_username)
    TextView tvUsername;
    @BindView(R2.id.tv_time)
    TextView tvTime;
    @BindView(R2.id.tv_content)
    TextView tvContent;
    @BindView(R2.id.gv)
    GridView gv;
    @BindView(R2.id.iv_thumb)
    ImageView ivThumb;
    @BindView(R2.id.tv_thumb)
    TextView tvThumb;
    @BindView(R2.id.iv_comment)
    ImageView ivComment;
    @BindView(R2.id.tv_comment)
    TextView tvComment;
    @BindView(R2.id.iv_share)
    ImageView ivShare;
    @BindView(R2.id.tv_share)
    TextView tvShare;
    @BindView(R2.id.expandlist)
    NestedExpandableListview expandlist;
    @BindView(R2.id.et_comment)
    FixedEditText etComment;

    private JSONObject json;
    private ArrayList<JSONObject> groupList;
    private ArrayList<ArrayList<JSONObject>> childList;
    private long bbsId;
    //记录edittext内内容是一级评论还是二级评论
    private int[] etTag;
    private int userId;
    //数据请求类型 获取评论
    private int GET_COMMENTS = 1;
    //数据请求类型 评论
    private int COMMENT = 2;
    //数据请求类型 点赞
    private int THUMB = 3;
    private int position;
    private int fromType;
    /**
     * 详情页跳转来源的类型，1是指来自点点圈首页帖子列表，2是指来自点点圈个人中心的帖子列表
     * 对二者做出区分的理由是为了对详情页点击用户头像和id能否跳转用户的个人中心做出区分
     * 来自首页的帖子可以跳转进入个人中心，来自个人中心的帖子就不能跳转了
     * 这是为了防止 首页点进帖子→帖子详情中进入个人中心→个人中心中帖子列表点进帖子详情→帖子详情点进个人中心的循环操作出现。
     */
    private int FROM_HOME = 1;
    private int FROM_INFO = 2;
    private String shareUrl;
    private String contents;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_moments_detail);
        ButterKnife.bind(this);
        init();
        getData();
    }

    private void init() {

        /**
         * edittext默认回复主贴,tag是数组，长度为1~2，第一位是0,1,2分别表示一级回复，二级回复，回复二级回复
         * 第二位是表示其所在的group索引号，一级回复没有
         */
        int[] ints = {0};
        etComment.setTag(ints);

        UserInfo userInfo = SessionManager.getDefault().getUser();
        userId = userInfo.getUserId();

        Intent intent = getIntent();
        String content = intent.getStringExtra("content");
        position = intent.getIntExtra("position", -1);
        fromType = intent.getIntExtra("fromType", -1);

        try {
            JSONObject job = new JSONObject(content);
            tvUsername.setText(job.optString("nickName"));
            tvThumb.setText(job.optString("clickCount"));
            tvComment.setText(job.optString("commentCount"));
            tvContent.setText(job.optString("contents"));
            tvTime.setText(job.optString("createDate"));
            ivThumb.setImageResource("1".equals(job.optString("state")) ? R.drawable.icon_thumb_red
                    : R.drawable.icon_thumb);
            bbsId = job.optLong("bbsId", -1);
            shareUrl = job.optString("shareUrl");
            contents = job.optString("contents");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getData() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("bbsId", bbsId);
        map.put("userId", userId);
        String url = ApiConstant.API_BASE_URL + "ddq/api/v1/article/findArticleDetail";

        netRequest(url, map, GET_COMMENTS);
    }

    //获取评论信息后更新ui的runnable
    Runnable r1 = new Runnable() {
        @Override
        public void run() {

            showBBSDetail();
        }
    };

    //回复后更新ui的runnable
    Runnable r2 = new Runnable() {
        @Override
        public void run() {

            etComment.getText().clear();
            etComment.setFixedText("");
            etComment.setHint("输入内容");
            if (!"0".equals(json.optString("code"))) {
                ToastUtils.showShortToast(json.optString("message"));
                return;
            }
            getData();
            ToastUtils.showShortToast(json.optString("message"));
        }
    };
    //点赞后更新ui的runnable
    Runnable r3 = new Runnable() {
        @Override
        public void run() {

            ToastUtils.showShortToast(json.optString("message"));
            if ("0".equals(json.optString("code"))) {
                if ("0".equals(json.optString("state"))) {
                    int i = Integer.parseInt(tvThumb.getText().toString());
                    ivThumb.setImageResource(R.drawable.icon_thumb);
                    i--;
                    tvThumb.setText(i + "");
                } else if ("1".equals(json.optString("state"))) {
                    int i = Integer.parseInt(tvThumb.getText().toString());
                    ivThumb.setImageResource(R.drawable.icon_thumb_red);
                    i++;
                    tvThumb.setText(i + "");
                }
            }
            getData();
        }
    };

    private void showBBSDetail() {
        if (json == null || !"0".equals(json.optString("code"))) {
            return;
        }
        JSONObject data = json.optJSONObject("data");
        JSONObject bbsJson = data.optJSONObject("bbs");
        tvUsername.setText(bbsJson.optString("nickName"));
        tvThumb.setText(bbsJson.optString("clickCount"));
        tvComment.setText(bbsJson.optString("commentCount"));
        tvContent.setText(bbsJson.optString("contents"));
        tvTime.setText(bbsJson.optString("createDate"));
        String state = bbsJson.optString("state");
        ivThumb.setImageResource("1".equals(state) ? R.drawable.icon_thumb_red : R.drawable.icon_thumb);
        shareUrl = bbsJson.optString("shareUrl");
        contents = bbsJson.optString("contents");

        JSONArray commentJsonArray = data.optJSONArray("comment");
        try {
            groupList = new ArrayList<>();
            childList = new ArrayList<>();
            for (int i = 0; i < commentJsonArray.length(); i++) {
                JSONObject job = commentJsonArray.getJSONObject(i);
                groupList.add(job);
                JSONArray childArray = job.optJSONArray("childComment");
                if (childArray == null) {
                    childList.add(null);
                } else {
                    ArrayList<JSONObject> childJob = new ArrayList<>();
                    for (int j = 0; j < childArray.length(); j++) {
                        childJob.add(childArray.getJSONObject(j));
                    }
                    childList.add(childJob);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (groupList != null && childList != null) {
            CommentsAadapter commentsAadapter = new CommentsAadapter(groupList, childList, etComment);
            expandlist.setAdapter(commentsAadapter);
            int count = expandlist.getCount();
            for (int i = 0; i < count; i++) {
                expandlist.expandGroup(i);
            }
        }
    }

    private void netRequest(final String url, final Map<String, Object> map, final int type) {
        AppUI.loading(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Gson gson = new Gson();
                String s = gson.toJson(map);
                RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .post(requestBody)
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    String string = response.body().string();
                    Log.i("jsonhhhh", string);
                    json = new JSONObject(string);
                    if (type == GET_COMMENTS) {
                        handler.post(r1);
                    } else if (type == COMMENT) {
                        handler.post(r2);
                    } else if (type == THUMB) {
                        handler.post(r3);
                    }
                    AppUI.dismiss();
                } catch (IOException e) {
                    AppUI.dismiss();
                    e.printStackTrace();
                } catch (JSONException e) {
                    AppUI.dismiss();
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Handler handler = new Handler();


    @OnClick(R2.id.iv_back)
    public void onFinish() {
        finish();
    }


    @Override
    public void finish() {
        //回调结果
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putInt("clickCount", Integer.parseInt(tvThumb.getText().toString()));
        bundle.putInt("commentCount", Integer.parseInt(tvComment.getText().toString()));
        if (json != null) {
            if (json.optJSONObject("data") != null && json.optJSONObject("data").optJSONObject("bbs") != null) {
                bundle.putString("state", json.optJSONObject("data").optJSONObject("bbs").optString("state"));
            }
        }
        bundle.putInt("position", position);
        intent.putExtras(bundle);
        setResult(1, intent);
        super.finish();
    }

    @OnClick(R2.id.iv_thumb)
    public void onThumbClicked() {
        String url = ApiConstant.API_BASE_URL + "/ddq/api/v1/dianzan/addDianzan ";
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("operationId", bbsId);
        netRequest(url, map, THUMB);
    }

    @OnClick(R2.id.tv_send)
    public void onSendClicked() {
        if ("".equals(etComment.getText().toString().trim())) {
            return;
        }

        etTag = (int[]) etComment.getTag();
        //一级评论
        if (etTag[0] == 0) {
            addParentComment();
            //二级评论
        } else if (etTag[0] == 1 || etTag[0] == 2) {
            addChildComment();
        }
    }

    private void addChildComment() {
        String url = ApiConstant.API_BASE_URL + "ddq/api/v1/comment/addParentChildComment";
        HashMap<String, Object> map = new HashMap<>();
        map.put("parentId", groupList.get(etTag[1]).optLong("parentId"));
        map.put("parentTime", groupList.get(etTag[1]).optString("createDate"));
        map.put("childId", userId);
        map.put("bbsId", bbsId);
        map.put("comment", etComment.getFixedText().trim() + etComment.getText().toString().trim());
        netRequest(url, map, COMMENT);
        //发完贴后，tag回归回复主楼
        etComment.setTag(new int[]{0});
    }

    private void addParentComment() {
        String url = ApiConstant.API_BASE_URL + "ddq/api/v1/comment/addComment";
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("bbsId", bbsId);
        map.put("content", etComment.getText().toString().trim());
        netRequest(url, map, COMMENT);

        etComment.setTag(new int[]{0});
    }

    @OnClick(R2.id.tv_content)
    public void onContentClicked() {
        etComment.getText().clear();
        etComment.setFixedText("");
        etComment.setHint("输入内容");
        int[] ints = {0};
        etComment.setTag(ints);
    }

    @OnClick(R2.id.iv_share)
    public void onShareClicked() {
        OnekeyShare oks = new OnekeyShare();
        oks.setTitle("点点淘金点点圈");
        oks.setTitleUrl(shareUrl);
        oks.setText(contents);
        oks.setUrl(shareUrl);
        Bitmap image = null;
        AssetManager assets = getResources().getAssets();
        try {
            InputStream is = assets.open("logo.png");
            image = BitmapFactory.decodeStream(is);
            is.close();
            oks.setImageData(image);
        } catch (IOException e) {
            e.printStackTrace();
        }

        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
            @Override
            public void onShare(Platform platform, Platform.ShareParams shareParams) {
                if ("ShortMessage".equals(platform.getName())) {
                    shareParams.setText("点点淘金点点圈：" + shareUrl);
                }
                if ("QQ".equals(platform.getName())) {
                    shareParams.setTitle("点点淘金点点圈");
                    shareParams.setText(contents);
                    shareParams.setTitleUrl(shareUrl);
                }

            }
        });
        oks.show(this);
    }

    @OnClick({R2.id.iv_avatar, R2.id.tv_username})
    public void onUserInfoClicked(View view) {
        JSONObject bbsJson = json.optJSONObject("bbs");
        Intent intent = new Intent();
        intent.putExtra("type",2);
        intent.putExtra("checkId", bbsJson.optString("userId"));
        intent.putExtra("userName", bbsJson.optString("nickName"));
        intent.putExtra("userAvatar",bbsJson.optString("userAvatar"));
    }
}
